package com.ssm.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.ssm.subject.common.enums.CategoryTypeEnum;
import com.ssm.subject.common.enums.IsDeletedFlagEnum;
import com.ssm.subject.domain.bo.SubjectLabelBO;
import com.ssm.subject.domain.convert.SubjectCategoryBOConverter;
import com.ssm.subject.domain.bo.SubjectCategoryBO;
import com.ssm.subject.domain.convert.SubjectLabelBOConverter;
import com.ssm.subject.domain.service.SubjectCategoryDomainService;
import com.ssm.subject.domain.util.CacheUtil;
import com.ssm.subject.infra.basic.entity.SubjectCategory;
import com.ssm.subject.infra.basic.entity.SubjectLabel;
import com.ssm.subject.infra.basic.entity.SubjectMapping;
import com.ssm.subject.infra.basic.service.SubjectCategoryService;
import com.ssm.subject.infra.basic.service.SubjectLabelService;
import com.ssm.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Log4j2
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {
    @Resource
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private ThreadPoolExecutor labelThreadPool; //名称注入

    @Resource
    private CacheUtil cacheUtil;

    /**
     * 添加分类
     * @param subjectCategoryBO
     */
    @Override
    public int add(SubjectCategoryBO subjectCategoryBO) {
        if(log.isInfoEnabled()) {
            log.info("SubjectCategoryDomainService.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryBOConverter.INSTANCE.convertBoToCatrgory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        return subjectCategoryService.insert(subjectCategory);
    }

    /**
     * 查询大分类 (大小分类共用一个xmlSql)
     * 查询题目数量：关联mapping和label表，根据label表的category_id(大分类id)得到label_id,
     * 用label_id去mapping(中category_id为小分类id)表查询subject_id 去重
     * @return
     */
    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryBOConverter.INSTANCE.convertBoToCatrgory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryBOConverter.INSTANCE.categoryListToBOList(subjectCategoryList);
        //只有大分类才查询题目数量，foreach时判空，避免空指针
        if(ObjectUtils.isEmpty(subjectCategoryBO.getParentId()) && !CollectionUtils.isEmpty(subjectCategoryBOList)) {
            subjectCategoryBOList.forEach(bo -> {
                bo.setCount(subjectCategoryService.querySubjectCount(bo.getId()));
            });
        }
        if(log.isInfoEnabled()) {
            log.info("SubjectCategoryDomainService.queryCategory.subjectCategoryBOList:{}", JSON.toJSONString(subjectCategoryBOList));
        }
        return subjectCategoryBOList;
    }

    /**
     * 更新分类
     * @param subjectCategoryBO
     */
    @Override
    public int update(SubjectCategoryBO subjectCategoryBO) {
        if(log.isInfoEnabled()) {
            log.info("SubjectCategoryDomainService.update.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryBOConverter.INSTANCE.convertBoToCatrgory(subjectCategoryBO);
        return subjectCategoryService.update(subjectCategory);
    }

    /**
     * 删除分类
     * @param subjectCategoryBO
     */
    @Override
    public int delete(SubjectCategoryBO subjectCategoryBO) {
        if(log.isInfoEnabled()) {
            log.info("SubjectCategoryDomainService.delete.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryBOConverter.INSTANCE.convertBoToCatrgory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        return subjectCategoryService.update(subjectCategory);
    }

    /**
     * 查询分类及标签一次性
     * 在原始的单线程下，subjectCategoryBOList会按照遍历顺序，去查询当前小分类下的标签集合。
     * 在多线程中，每个线程执行完成的顺序不一致，当subjectCategoryBOList每一个元素去set LabelList时，要先知道标签集合属于哪一个分类下的，所以使用map集合映射。
     * @param subjectCategoryBO
     * @return
     */
    @Override
    @SneakyThrows
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        String cacheKey = "categoryAndLabel." + subjectCategoryBO.getId();
//        List<SubjectCategoryBO> resultList = cacheUtil.getResult(cacheKey, SubjectCategoryBO.class, new Function<String, List>() {
//            @Override
//            public List apply(String key) {
//                return getSubjectCategoryBOS(subjectCategoryBO.getId());
//            }
//        });
        List<SubjectCategoryBO> resultList = cacheUtil.getResult(cacheKey, SubjectCategoryBO.class, (key) -> getSubjectCategoryBOS(subjectCategoryBO.getId()));
        return resultList;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        if(log.isInfoEnabled()) {
            log.info("SubjectCategoryDomainService.queryCategoryAndLabel.bo:{}", JSON.toJSONString(categoryId));
        }
        //查询大分类下的小分类
        SubjectCategory subjectCategory = new SubjectCategory(); //bo中代入了id，此处不使用convert转化
        subjectCategory.setParentId(categoryId);
        subjectCategory.setCategoryType(CategoryTypeEnum.SECOND.getCode());
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryBOConverter.INSTANCE.categoryListToBOList(subjectCategoryList);
        //一次获取标签信息 -- 线程池并发调用
        if(!CollectionUtils.isEmpty(subjectCategoryBOList)) {
//            //此时进行多线程查询，有多个线程任务同时运行，使用List存储
//            List<FutureTask<Map<Long, List<SubjectLabelBO>>>> futureTaskList = new LinkedList<>();
//            subjectCategoryBOList.forEach(category -> {
//                FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask = new FutureTask<>(() -> getLabelBoList(category));
//                futureTaskList.add(futureTask);
//                //FutureTask为任务对象，使用线程池进行提交执行
//                labelThreadPool.submit(futureTask);
//            });
//
              Map<Long, List<SubjectLabelBO>> map = new HashMap<>();
//            for(FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask : futureTaskList) {
//                //主线程阻塞等待异步线程执行完毕，获取返回结果
//                Map<Long, List<SubjectLabelBO>> resultMap = futureTask.get();
//                if(CollectionUtils.isEmpty(resultMap)) continue;
//                map.putAll(resultMap); //putAll把一个map的值存到另一个map
//            }

            /**
             * CompletableFuture.supplyAsync创建带有返回值的异步任务,并向线程池提交
             */
            List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = subjectCategoryBOList.stream()
                    .map(category -> CompletableFuture.supplyAsync(() -> getLabelBoList(category), labelThreadPool))
                    .collect(Collectors.toList());

            //主线程阻塞等待异步线程执行完毕，获取返回结果
            completableFutureList.forEach(future -> {
                try {
                    Map<Long, List<SubjectLabelBO>> map1 = future.get();
                    map.putAll(map1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            //最后进行labelBoList的组装
            subjectCategoryBOList.forEach(categoty -> categoty.setLabelBOList(map.get(categoty.getId())));
        }
        return subjectCategoryBOList;
    }

    private Map<Long, List<SubjectLabelBO>> getLabelBoList(SubjectCategoryBO bo) {
        Map<Long, List<SubjectLabelBO>> labelMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(bo.getId());
        //获取 题目_标签_分类 的实体对象
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryByLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(subjectMappingList)) {
            return null;
        }
        //根据标签id获取标签对象
        List<Long> labelIds = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabelList = subjectLabelService.queryByLabelIds(labelIds);
        List<SubjectLabelBO> subjectLabelBOList = SubjectLabelBOConverter.INSTANCE.LabelListToLabelBoList(subjectLabelList);
        labelMap.put(bo.getId(), subjectLabelBOList);
        return labelMap;
    }
}
